package com.guojian.jdbc.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.jdbc.core.ColumnMapRowMapper;

import com.google.common.collect.Maps;
import com.guojian.common.utils.StringUtilss;
import com.guojian.jdbc.JdbcDataFormat;

public class ColumnMapDataFormatRowMapper extends ColumnMapRowMapper {

	private JdbcDataFormat<Map<String, Object>> format;

	public ColumnMapDataFormatRowMapper() {
	}

	public ColumnMapDataFormatRowMapper(JdbcDataFormat<Map<String, Object>> format) {
		this.format = format;
	}

	@Override
	public Map<String, Object> mapRow(ResultSet rs, int rowNum) throws SQLException {
		Map<String, Object> rowMap = super.mapRow(rs, rowNum);
		Set<String> keys = rowMap.keySet();

		Map<String, Object> newRowMap = Maps.newLinkedHashMap();
		for (String key : keys) {
			String newKey = StringUtilss.toLowerCaseOfHump(key);// 驼峰格式(大写转小写并且_后面的字母大写)AAA_a-->aaaA
			if (!rowMap.containsKey(newKey)) {
				newRowMap.putIfAbsent(newKey, rowMap.get(key));
			}
		}
		newRowMap.putAll(rowMap);
		if (getFormat() != null) {
			this.format.formatRow(newRowMap);
		}
		return newRowMap;
	}

	public JdbcDataFormat<Map<String, Object>> getFormat() {
		return format;
	}

	public void setFormat(JdbcDataFormat<Map<String, Object>> format) {
		this.format = format;
	}

	public static void main(String[] args) {

		// Map<String, Object> rowMap = new LinkedCaseInsensitiveMap<>();
		// rowMap.put("PROJECTNAME", "AAAAAAAAAAAAA");

		Map<String, Object> rowMap = new LinkedHashMap<>();
		rowMap.put("projectname", "AAAAAAAAAAAAA1");
		rowMap.put("PROJECTNAME", "AAAAAAAAAAAAA2");

		Map<String, Object> newRowMap = Maps.newConcurrentMap();
		newRowMap.put("projectname", "aaaaaaaaaaaaaaaaaaaaaaa");

		rowMap.putAll(newRowMap);
		//System.out.println("JSON.toJSONString(rowMap) = " + JSON.toJSONString(rowMap));

	}
}
